/**
 * Copyright 2008 Hotye Inc.
 */
package craneding.gwt.databean.client.ui.field;

import craneding.gwt.databean.client.model.FieldInfo;

/**
 * Field Input 辅助工具
 * 
 * @author crane.ding
 * @version 1.0 2008-12-1
 */
public class FieldInputUtil {
	private static Class<?>[] numberClass = new Class<?>[] { byte.class,
			Byte.class, short.class, Short.class, int.class, Integer.class,
			long.class, Long.class, float.class, Float.class, double.class,
			Double.class };

	/**
	 * 通过FieldInfo验证
	 * 
	 * @param fieldInfo
	 *            FieldInfo信息
	 * @param text
	 *            需验证的字符串
	 * @return 错误信息,NULL则为验证通过
	 */
	public static String validateByFieldInfo(FieldInfo fieldInfo, String text) {
		if (text.trim().equals("") && fieldInfo.required())// 必填项.
			return fieldInfo.label().concat("必须填写.");
		int length = fieldInfo.length();
		if (length != -1 && text.trim().length() > length)// 长度不能大于用户定义的长度
			return fieldInfo.label().concat("不能大于" + length + "个字符.");
		String regex = fieldInfo.regexp();// 用户自定义的正则表达式.
		if (!regex.equals("") && !text.matches(regex))// 校验用户的自定义表达式,校验结果不符合.
			return fieldInfo.label().concat("格式错误.");
		return null;
	}

	public static boolean isNumberType(Class<?> datatype) {
		for (Class<?> type : numberClass) {
			if (type == datatype)
				return true;
		}
		return false;
	}

	public static boolean isBaseNumberType(Class<?> clazz) {
		if (clazz == byte.class || clazz == short.class || clazz == int.class
				|| clazz == long.class || clazz == float.class
				|| clazz == double.class) {
			return true;
		}
		return false;
	}
}
